﻿CREATE PROCEDURE [ServiceEngine].[CreateSchemaImport]
@SchemaID UNIQUEIDENTIFIER, @ImportNamespace NVARCHAR (256), @ID UNIQUEIDENTIFIER OUTPUT
AS
BEGIN
	DECLARE @ErrorMessage NVARCHAR(4000);
	DECLARE @ErrorSeverity INT;
	DECLARE @ErrorState INT;
	
	SET NOCOUNT ON;

	SELECT @ID = SchemaImportID FROM ServiceEngine.SchemaImports WHERE SchemaID = @SchemaID AND ImportNamespace = @ImportNamespace
	
	BEGIN TRY
		-- Check to make sure that the reference is not already there
		IF @ID IS NULL
		BEGIN				
			SELECT @ID = EntityID FROM ServiceEngine.[Names] WHERE EntityName = @ImportNamespace
			--Do not reference a schema to itself
			IF NOT(@ID = @SchemaID) 
			BEGIN
				BEGIN TRANSACTION
						SET @ID = newid();
						INSERT INTO ServiceEngine.SchemaImports (SchemaImportID, SchemaID, ImportNamespace)
						VALUES (@ID, @SchemaID, @ImportNamespace)
				COMMIT TRANSACTION
			END
		END
	END TRY
	BEGIN CATCH
		SELECT 
			@ErrorMessage = ERROR_MESSAGE(),
			@ErrorSeverity = ERROR_SEVERITY(),
			@ErrorState = ERROR_STATE();

		IF XACT_STATE() <> 0 ROLLBACK TRANSACTION;

		RAISERROR (@ErrorMessage, 
				   @ErrorSeverity,
				   1);
	END CATCH
END

